<script setup lang="ts">
import { reactive, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { useDebounceFn } from '@vueuse/core';
import {
  Col,
  DatePicker,
  Form,
  FormItem, Input,
  InputNumber,
  message,
  Row,
  Select,
  Switch,
  Table,
} from 'ant-design-vue';

import { DictAddInit } from '#/api/goods';
import { createOrder, getCompanyList, getPurchaser } from '#/api/spuBom';

const emit = defineEmits(['refresh']);

const selectRows = ref([]);

const columns1: any = [
  {
    title: 'BOM类型',
    dataIndex: 'bom_name',
    key: 'bom_name',
    align: 'center',
  },
  {
    title: '实际面料',
    children: [
      {
        title: '面料名称',
        dataIndex: 'material_name',
        key: 'material_name',
        align: 'center',
      },
      {
        title: '本次供应商',
        dataIndex: 'SupplyNa',
        key: 'SupplyNa',
        align: 'center',
      },
      {
        title: '单价',
        dataIndex: 'price',
        key: 'price',
        align: 'center',
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
      },
    ],
  },
  {
    title: '采购员',
    dataIndex: 'purchase_user',
    key: 'purchase_user',
    align: 'center',
    width: 250,
  },
  {
    title: '下单数量',
    dataIndex: 'num',
    key: 'num',
    align: 'center',
  },
  {
    title: '交期',
    dataIndex: 'dead_line',
    key: 'dead_line',
    align: 'center',
  },
  {
    title: '其他结算方式备注',
    dataIndex: 'other_pay_remark',
    key: 'other_pay_remark',
    align: 'center',
    resizable: true,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
    resizable: true,
  },
]

const Options = ref([]);
const loading = ref(false);
const handleSupplySearch = useDebounceFn(async (keyword) => {
  loading.value = true;
  try {
    const res = await getPurchaser({
      quick_search: keyword || '',
      page: 1,
      limit: 9999,
      group_id: 7,
      initKey: 'id',
      select: true,
    });

    Options.value = res.data.data.list.map((it) => ({
      label: it.realname,
      value: it.id,
    }));
  } finally {
    loading.value = false;
  }
}, 300);

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const handleSupplyDropdown = (open) => {
  if (open && Options.value.length === 0) {
    handleSupplySearch('');
  }
};
const [Modal, modalApi] = useVbenModal({
  class: 'w-2/3',

  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    save()
  },
  onOpenChange: async (isOpen: boolean) => {
    getCompanyList().then((res) => {
      companyList.value = res.map((item: any) => ({
        value: item.id,
        label: item.name,
      }));
    });
    DictAddInit({ keys: ['paymentMethod', 'paymentRule'], type: 2 }).then(
      (result: any) => {
        paymentMethod.value = result.select_list.paymentMethod.map(
          (item: any) => ({
            label: item.name,
            value: item.value,
            code: item.name,
            id: Number(item.id),
          }),
        );
        // 初始化结算规则并添加禁用状态
        paymentRule.value = result.select_list.paymentRule.map((item: any) => ({
          label: item.name,
          value: item.name,
          code: item.value,
          disabled: false,
        }));
        formModel.fk_type = paymentMethod.value[0].value;
        changeType(formModel.fk_type);
      },
    );

    handleSupplySearch('');
    if (!isOpen) return;
    const { data, id, purchase_id } = modalApi.getData<Record<string, any>>();
    formModel.id = id;
    selectRows.value = data;
    formModel.purchase_id = purchase_id;
  },
});
const save = useDebounceFn(() => {
  const params = {
    formData: {
      fk_type: formModel.fk_type,
      fk_rule: formModel.fk_rule,
      is_send_work_notice: formModel.is_send_work_notice ? 1 : 0,
      purchase_name: formModel.purchase_name,
      order_list: selectRows.value.map((item) => ({
        ...(item as Record<string, any>),
        goods_purchase_id: formModel.purchase_id,
        purchase_date: new Date().toISOString().split('T')[0],
      })),
      id: formModel.id,
    },
  };

  modalApi.lock(true);
  createOrder(params).then((res: any) => {
    modalApi.unlock();
    if (res.data.code === 1) {
      message.success(res.data.msg);
      modalApi.close();
      emit('refresh');
    } else {
      message.error(res.data.msg);
    }
  });
}, 300);
function changeType(data: any) {
  formModel.fk_rule = '';
  paymentRule.value = paymentRule.value?.map((item: any) => ({
    ...item,
    disabled: item.code !== data,
  }));
}

const formModel = reactive({
  fk_type: '',
  purchase_name: '',
  fk_rule: '',
  id: '',
  purchase_id: '',
  is_send_work_notice: false,
});

const companyList = ref([]);
const paymentMethod = ref([]);
const paymentRule = ref([]);
</script>

<template>
  <Modal title="确认下单？">
    <Page>
      <Form :label-col="{ span: 7.5 }" :model="formModel">
        <Row :gutter="[15, 0]">
          <Col :span="6">
            <FormItem name="reqCode" label="下单方(主体)">
              <Select
                v-model:value="formModel.purchase_name"
                show-search
                allow-clear
                style="width: 100%; height: 100%"
                placeholder="请输入"
                :options="companyList"
              />
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem name="reqCode" label="结算方式">
              <Select
                v-model:value="formModel.fk_type"
                @change="changeType"
                show-search
                allow-clear
                style="width: 100%; height: 100%"
                placeholder="请输入"
                :options="paymentMethod"
              />
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem name="reqCode" label="结算规则">
              <Select
                v-model:value="formModel.fk_rule"
                show-search
                allow-clear
                style="width: 100%; height: 100%"
                placeholder="请输入"
                :options="paymentRule"
              />
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem name="reqCode" label="工作通知跟单">
              <Switch v-model:checked="formModel.is_send_work_notice" />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <Table
        class="w-fill"
        bordered
        :data-source="selectRows"
        :columns="columns1"
        :pagination="false"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'purchase_user'">
            <Select
              v-model:value="record.purchase_user"
              show-search
              allow-clear
              style="width: 100%; height: 100%"
              placeholder="请输入"
              :filter-option="false"
              :options="Options"
              :loading="loading"
              @search="handleSupplySearch"
              @dropdown-visible-change="handleSupplyDropdown"
            />
          </template>
          <template v-if="column.dataIndex === 'num'">
            <InputNumber v-model:value="record.num" />
          </template>
          <template v-if="column.dataIndex === 'dead_line'">
            <DatePicker
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              v-model:value="record.dead_line"
            />
          </template>
          <template v-if="column.dataIndex === 'other_pay_remark'">
            <Input v-model:value="record.other_pay_remark" />
          </template>
          <template v-if="column.dataIndex === 'remark'">
            <Input v-model:value="record.remark" />
          </template>
        </template>
      </Table>
    </Page>
  </Modal>
</template>

<style scoped></style>
